<template>
  <div class="map-container">
    <div ref="mapContainer" class="map-view"></div>

    <!-- 地图加载状态 -->
    <div v-if="loading" class="loading-overlay">
      <div class="loading-spinner">🎣</div>
      <div class="loading-text">正在加载地图...</div>
    </div>

    <!-- 错误提示 -->
    <div v-if="error" class="error-overlay">
      <div class="error-content">
        <div class="error-icon">⚠️</div>
        <div class="error-text">{{ error }}</div>
        <div class="error-details" v-if="showDebug">
          <small>调试信息：请检查控制台日志</small>
        </div>
      </div>
    </div>

    <!-- 钓点圈编辑组件 -->
    <FishingCircleEditor 
        v-if="showCircleEditor" 
        :visible="showCircleEditor"
        :points="circlePoints"
        @close="closeCircleEditor"
      />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { mapController } from './MapController'
import FishingCircleEditor from './pages/circle/FishingCircleEditor.vue'

// 定义props
const props = defineProps({
  isLoggedIn: {
    type: Boolean,
    default: false
  }
})

// 定义emits
const emit = defineEmits(['mapReady', 'mapError'])

// 响应式数据
const mapContainer = ref<HTMLDivElement>()
const map = ref<any>(null)
const loading = ref(true)
const error = ref('')
const showDebug = ref(false)
const showCircleEditor = ref(false)
const circlePoints = ref<Array<{lat: number, lng: number}>>([])


// 获取用户位置并移动地图
const getUserLocationAndMoveMap = async () => {
  if (!map.value) {
    console.warn('地图尚未初始化，无法获取位置')
    return
  }

  const qq = (window as any).qq
  
  try {
    // 使用浏览器地理位置API
    if ('geolocation' in navigator) {
      console.log('开始获取用户位置...')
      
      navigator.geolocation.getCurrentPosition(
        (position) => {
          const userLat = position.coords.latitude
          const userLng = position.coords.longitude
          
          console.log('获取到用户位置:', { lat: userLat, lng: userLng })
          
          // 创建用户位置坐标
          const userLocation = new qq.maps.LatLng(userLat, userLng)
          
          // 移动地图到用户位置
          map.value.setCenter(userLocation)
          map.value.setZoom(15)
          
          // 添加用户位置标记
          const marker = new qq.maps.Marker({
            position: userLocation,
            map: map.value,
            title: '我的位置'
          })
          
          console.log('地图已移动到用户位置')
        },
        (error) => {
          console.warn('获取位置失败:', error.message)
          // 如果获取位置失败，使用默认位置
          console.log('使用默认位置')
        },
        {
          enableHighAccuracy: true,
          timeout: 10000,
          maximumAge: 300000
        }
      )
    } else {
      console.warn('浏览器不支持地理位置API')
    }
  } catch (error: any) {
    console.error('获取位置时出错:', error)
  }
}

// 地图初始化
const initializeMap = async () => {
  loading.value = true
  error.value = ''
  showDebug.value = false

  console.log('开始初始化腾讯地图...')

  try {
  //  await loadTencentMapScript()

    const qq = (window as any).qq
    
    if (!mapContainer.value) {
      throw new Error('地图容器未找到')
    }

    console.log('创建腾讯地图实例...')
    
    try {
      // 初始化地图
      map.value = new qq.maps.Map(mapContainer.value, {
        center: new qq.maps.LatLng(39.915, 116.404),
        zoom: 13,
        panControl: false,
        zoomControl: false,
        mapTypeControl: false
      })
      
      console.log('腾讯地图实例创建成功:', map.value)
      
      // 验证地图是否成功创建
      if (!map.value || typeof map.value.setCenter !== 'function') {
        throw new Error('地图实例创建失败')
      }

      loading.value = false
      emit('mapReady', map.value)
      console.log('地图初始化完成')
      
      // 设置地图实例到MapController
      mapController.setMap(map.value)
      
      // 地图初始化完成后获取用户位置
      getUserLocationAndMoveMap()
      
    } catch (mapError) {
      console.error('创建地图实例时出错:', mapError)
      throw new Error(`地图创建失败: ${mapError instanceof Error ? mapError.message : '未知错误'}`)
    }

  } catch (err: any) {
    console.error('地图初始化失败:', err)
    error.value = err.message || '地图初始化失败'
    loading.value = false
    emit('mapError', error.value)
  }
}

// 生命周期钩子
onMounted(() => {
  initializeMap()
})

// CircleEditor方法
const openCircleEditor = (points: Array<{lat: number, lng: number}>) => {
  circlePoints.value = points
  showCircleEditor.value = true
}

const closeCircleEditor = () => {
  showCircleEditor.value = false
  circlePoints.value = []
}

// 监听polygon-complete事件
onMounted(() => {
  const handlePolygonComplete = (event: CustomEvent) => {
    openCircleEditor(event.detail.points)
  }
  
  window.addEventListener('polygon-complete', handlePolygonComplete as EventListener)
  
  onUnmounted(() => {
    window.removeEventListener('polygon-complete', handlePolygonComplete as EventListener)
  })
})

// 暴露方法给父组件
defineExpose({
  initializeMap,
  getUserLocationAndMoveMap
})

onUnmounted(() => {
  if (map.value) {
    map.value = null
  }
})
</script>

<style scoped>


/* 在全局 CSS 中添加（确保生效范围覆盖地图容器） */
.qqmap-infowindow-close {
  display: none !important; /* 强制隐藏关闭按钮 */
}

/* 可选：如果还有其他关闭相关元素，一并隐藏 */
.qqmap-infowindow .close {
  display: none !important;
}
.map-container {
  position: relative;
  overflow: hidden;
  border: none;
  background: var(--bg-primary);
  width: 100%;
  height: 100%;
}

.map-view {
  width: 100%;
  height: 100%;
}

.loading-overlay,
.error-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: var(--bg-overlay);
  color: var(--text-primary);
  z-index: 2000;
}

.loading-spinner {
  font-size: 48px;
  animation: bounce 1s infinite;
}

.loading-text,
.error-text {
  margin-top: 16px;
  font-size: 16px;
}

.error-content {
  text-align: center;
}

.error-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.retry-btn {
  margin-top: 16px;
  padding: 8px 16px;
  background: var(--accent-primary);
  color: var(--text-inverse);
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  margin-right: 8px;
}

.debug-btn {
  margin-top: 16px;
  padding: 8px 16px;
  background: var(--bg-tertiary);
  color: var(--text-primary);
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.error-details {
  margin-top: 8px;
  color: var(--text-secondary);
}

.retry-btn:hover {
  background: var(--accent-primary-hover);
}

@keyframes bounce {
  0%, 100% { transform: translateY(0); }
  50% { transform: translateY(-10px); }
}

@media (max-width: 768px) {
  .map-container.has-sidebar {
    margin-left: 0;
  }
  
  .map-controls {
    top: 10px;
    right: 10px;
  }
  
  .map-btn {
    padding: 6px 10px;
    font-size: 11px;
  }
}
</style>